package api

import (
	"api/internal/api/request"
	"api/internal/api/response"
	"api/internal/handler"
	"common/consulinit"
	"flag"
	"github.com/gin-gonic/gin"
	"strconv"
	ticket "ticket_srv/proto"
)

var (
	ticketAddress = "127.0.0.1:50052"
	ticketServer  = flag.String("ticket", ticketAddress, "The server address")
	ticketSrv     = handler.ServerNewClient().TicketServer(ticketServer)
)

func RegisterTicket() {
	registration := consulinit.ServiceRegistration{
		Name:    "ticket_srv",
		Address: "117.27.231.112",
		Port:    50052,
		Tags:    nil,
	}
	consulinit.RegisterService(registration)
}

func FindDate(c *gin.Context) {
	RegisterTicket()
	var json *request.FindDate
	if err := c.ShouldBindJSON(&json); err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	date, err := ticketSrv.FindDate(c, &ticket.FindDateRequest{Date: json.Date})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	response.Response(c, 200, "查询成功", date)
}

func FindTicket(c *gin.Context) {
	RegisterTicket()
	value, _ := c.Get("userId")
	userId, _ := strconv.Atoi(value.(string))
	findTicket, err := ticketSrv.FindTicket(c, &ticket.FindTicketRequest{UserId: int64(userId)})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	response.Response(c, 200, "查询成功", findTicket)
}

func CreateTicket(c *gin.Context) {
	RegisterTicket()
	value, _ := c.Get("userId")
	userId, _ := strconv.Atoi(value.(string))
	var json *request.CreateTicket
	if err := c.ShouldBindJSON(&json); err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	createTicket, err := ticketSrv.CreateTicket(c, &ticket.CreateTicketRequest{
		UserId:   int64(userId),
		TicketId: int64(json.TicketId),
		Seat:     int64(json.Seat),
	})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	response.Response(c, 200, "购票成功", createTicket)
}

func FindSeat(c *gin.Context) {
	RegisterTicket()
	var json *request.FindSeat
	if err := c.ShouldBindJSON(&json); err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	seat, err := ticketSrv.FindSeat(c, &ticket.FindSeatRequest{TicketId: int64(json.TicketId)})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	response.Response(c, 200, "座位查询成功", seat)
}
